<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="paperTitle">
        <el-input
          v-model="queryParams.paperTitle"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createUserName">
        <el-input
          v-model="queryParams.createUserName"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search"  @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"

          @click="handleAdd"
          v-hasPermi="['system:paper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"

          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:paper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"

          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:paper:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"

          @click="handleExport"
          v-hasPermi="['system:paper:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <SmartTable v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试卷名称" align="center" prop="paperTitle" />
      <el-table-column label="是否开启" align="center" prop="isOpen">
        <template #default="{ row }">
          <el-tag v-if="row.isOpen === 0" type="warning">草稿</el-tag>
          <el-tag v-if="row.isOpen === 1" type="success">开启</el-tag>
          <el-tag v-if="row.isOpen === 2" type="info">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人账号" align="center" prop="createUserCode" />
      <el-table-column label="创建人姓名" align="center" prop="createUserName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:paper:edit']"
          >修改</el-button>
          <el-button

            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:paper:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </SmartTable>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改试卷对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="试卷名称" prop="paperTitle">
              <el-input v-model="form.paperTitle" placeholder="请输入试卷名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否开启" prop="isOpen">
              <el-radio-group v-model="form.isOpen">
                <el-radio :value="0">草稿</el-radio>
                <el-radio :value="1">开启</el-radio>
                <el-radio :value="2">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <div>试题列表</div>
              <el-button icon="Plus" type="primary" @click="addQuestion">新增试题</el-button>
            </div>
          </template>
          <div style="max-height: 650px;overflow-y: auto; overflow-x: hidden">
            <div v-for="(item, index) in form.examQuestionList" :key="index + 'q'">
              <el-divider>
                第{{ index + 1 }}题
                <el-popconfirm title="确定要删除这个试题?" @confirm="form.examQuestionList.splice(index, 1)">
                  <template #reference>
                    <el-button type="text" icon="Delete">删除</el-button>
                  </template>
                </el-popconfirm>
              </el-divider>
              <el-row :gutter="12">
                <el-col :span="12">
                  <el-form-item label="题目类型">
                    <el-radio-group v-model="item.questionType">
                      <el-radio-button value="CHOICE">选择题</el-radio-button>
                      <el-radio-button value="INPUT">输入题</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="分值" prop="score">
                    <el-input v-model="item.score" placeholder="请输入分值" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="题目内容">
                <el-input v-model="item.questionText" placeholder="请输入内容" />
              </el-form-item>
              <el-form-item v-if="item.questionType === 'CHOICE'" label="题目选项">
                <table class="table">
                  <tr>
                    <th>选项内容</th>
                    <th width="100px">是否正确</th>
                    <th width="100px">
                      <el-button
                        type="text"
                        icon="Plus"
                        @click="item.examQuestionOptionList.push({})"
                      >新增</el-button>
                    </th>
                  </tr>
                  <tr v-for="(option, i) in item.examQuestionOptionList" :key="index + i + 'o'">
                    <td>
                      <el-input v-model="option.optionText" placeholder="请输入选项内容" />
                    </td>
                    <td>
                      <el-checkbox :true-value="1" :false-value="0" v-model="option.isCorrect"></el-checkbox>
                    </td>
                    <td>
                      <el-button
                        type="text"
                        icon="Delete"
                        danger
                        @click="item.examQuestionOptionList.splice(i, 1)"
                      >删除</el-button>
                    </td>
                  </tr>
                </table>
              </el-form-item>
            </div>
          </div>
        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPaper, getPaper, delPaper, addPaper, updatePaper } from "@/api/system/paper"
import SmartTable from '@/components/SmartTable/index.vue'
export default {
  name: "Paper",
  components: {SmartTable},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷表格数据
      paperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paperTitle: null,
        isOpen: null,
        createUserCode: null,
        createUserName: null,
        updateUserCode: null,
        updateUserName: null,
      },
      // 表单参数
      form: {
        examQuestionList: [],
      },
      // 表单校验
      rules: {
        paperTitle: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" }
        ],
        isOpen: [
          { required: true, message: "是否开启不能为空" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询试卷列表 */
    getList() {
      this.loading = true
      listPaper(this.queryParams).then(response => {
        this.paperList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        paperTitle: null,
        isOpen: null,
        createUserCode: null,
        createUserName: null,
        updateUserCode: null,
        updateUserName: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加试卷";
      this.form = {
        isOpen: 0,
        examQuestionList: []
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPaper(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改试卷"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!this.form.examQuestionList.length) {
          return this.$modal.msgError("请至少添加一道试题")
        }
        let hasError = false;
        this.form.examQuestionList.forEach((item, i) => {
          if (!item.questionText) {
            hasError = true;
            this.$modal.msgError(`第${i+1}题请输入题目内容`)
          } else {
            if (item.questionType === 'CHOICE') {
              const examQuestionOptionList = item.examQuestionOptionList.filter(option => option.optionText);
              if (!examQuestionOptionList.length) {
                hasError = true;
                this.$modal.msgError(`第${i+1}题是选择题，请至少录入一个选项`)
              }
            }
          }
        });
        if (hasError) {
          return;
        }
        if (valid) {
          if (this.form.id != null) {
            updatePaper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除试卷编号为"' + ids + '"的数据项？').then(function() {
        return delPaper(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/paper/export', {
        ...this.queryParams
      }, `paper_${new Date().getTime()}.xlsx`)
    },

    addQuestion() {
      this.form.examQuestionList.push({ examQuestionOptionList: [], questionType: 'CHOICE' });
    },
  }
}
</script>
<style lang="scss">
  .card-header {
    display: flex;
    justify-content: space-between;
  }
  .table {
    width: 100%;
    text-align: center;
    border-collapse: collapse;
    td, th {
      border: 1px solid #ccc;
    }
  }
</style>
